import 'package:fishing/providers/user_provider.dart';
import 'package:fishing/utils/storage_util.dart';
import 'package:flutter/material.dart';
import '../services/auth_service.dart';
import '../services/websocket_manager.dart';

class AuthProvider with ChangeNotifier {
  final AuthService _authService = AuthService();
  final WebSocketManager _wsManager = WebSocketManager();

  bool _isLoading = false;
  bool get isLoading => _isLoading;

  bool _loginLoading = false;
  bool get loginLoading => _loginLoading;

  bool _isLoggedIn = false;
  bool get isLoggedIn => _isLoggedIn;

  bool _isInitialized = false;
  bool get isInitialized => _isInitialized;

  String? _lastError;
  String? get lastError => _lastError;

  AuthProvider() {
    _initializeAuth();
  }

  /// 获取验证码
  Future<bool> fetchSmsCode(String phone) async {
    _setLoading(true);
    _lastError = null;
    try {
      await _authService.getSmsCode(phone);
      return true;
    } catch (e) {
      debugPrint('获取验证码失败: $e');
      _lastError = '获取验证码失败，请稍后重试';
      return false;
    } finally {
      _setLoading(false);
    }
  }

  Future<bool> login(String phone, String code,UserProvider userProvider) async {
    _setLoginLoading(true);
    _lastError = null;
    try {
      final success = await _authService.login(phone, code);
      
      if (success) {
        _isLoggedIn = true;
        await userProvider.fetchUserInfo();
        
        // 登录成功后连接WebSocket
        if (userProvider.user != null) {
          try {
            await _wsManager.connectWithUser(userProvider.user!.userId.toString());
            debugPrint('用户登录时连接WebSocket成功: userId=${userProvider.user!.userId}');
          } catch (e) {
            debugPrint('用户登录时WebSocket连接失败: $e');
            // WebSocket连接失败不影响登录流程
          }
        }
        
        notifyListeners();  
        return true;
      } else {
        _lastError = '登录失败，请检查手机号和验证码';
        return false;
      }
    } catch (e) {
      debugPrint('登录失败: $e');
      _lastError = '登录失败，网络异常请稍后重试';
      return false;
    } finally {
      _setLoginLoading(false);
    }
  }

  /// 设置验证码加载状态
  void _setLoading(bool value) {
    _isLoading = value;
    notifyListeners();
  }

  /// 设置登录加载状态
  void _setLoginLoading(bool value) {
    _loginLoading = value;
    notifyListeners();
  }

  Future<bool> logout() async{
    try {
      await _authService.logout();
    } catch (e) {
      debugPrint('调用登出接口失败: $e');
      // 即使接口调用失败，也要清除本地状态
    }
    
    // 清除本地存储
    await StorageUtil.clearToken();
    
    // 登出时断开WebSocket连接（添加超时处理，不阻塞退出流程）
    _wsManager.disconnect().timeout(
      const Duration(seconds: 2),
      onTimeout: () {
        debugPrint('WebSocket断开连接超时，强制继续退出流程');
      },
    ).then((_) {
      debugPrint('用户登出时断开WebSocket连接成功');
    }).catchError((e) {
      debugPrint('用户登出时断开WebSocket连接失败: $e');
    });
    
    _isLoggedIn = false;
    debugPrint('用户已登出，isLoggedIn: $_isLoggedIn');
    
    // 只触发一次通知，避免重复通知导致路由循环
    notifyListeners();
    
    return true;
  }

  /// 初始化认证状态 - 检查本地token
  Future<void> _initializeAuth() async {
    try {
      final isLoggedIn = await StorageUtil.isLoggedIn();
      _isLoggedIn = isLoggedIn;
      
      if (isLoggedIn) {
        // 检查token是否即将过期
        final isExpiringSoon = await StorageUtil.isTokenExpiringSoon();
        if (isExpiringSoon) {
          // 可以在这里添加刷新token的逻辑
        }
      }
    } catch (e) {
      _isLoggedIn = false;
    } finally {
      _isInitialized = true;
      notifyListeners();
    }
  }

  /// 手动检查登录状态
  Future<void> checkLoginStatus() async {
    final isLoggedIn = await StorageUtil.isLoggedIn();
    if (_isLoggedIn != isLoggedIn) {
      _isLoggedIn = isLoggedIn;
      notifyListeners();
    }
  }

  /// 设置登录状态
  void setLoggedIn(bool value) {
    _isLoggedIn = value;
    notifyListeners();
  }
}
